<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use app\common\facade\model\AdminModel;
use app\common\facade\model\AdminRoleModel;
use app\common\facade\model\AdminRuleModel;

class Admin extends BaseAdmin
{
    /**
     * 管理员列表
     */
    public function adminList($param = [])
    {
        $whereAdmin = [];

        $ordername = 'id';
        $order = 'asc';
        if($param['ordername'] && $param['order']) {
            $ordername = $param['ordername'];
            $order = $param['order'] == 'descending' ? 'desc' : 'asc';
        }
        
        if (isset($param['query']) && !empty($param['query'])) $whereAdmin[] = ['username', 'like', "%{$param['query']}%"];

        $adminList = AdminModel::adminList($whereAdmin, [], $param['offset'], $param['length'], $ordername, $order);

        return $adminList;
    }

    /**
     * 管理员详情
     */
    public function adminInfo($param = [])
    {
        
        if (isset($param['username'])) $where[] = ['username', '=', $param['username']];
        
        if (isset($param['access_login'])) $where[] = ['access_login', '=', $param['access_login']];

        if (isset($param['enable'])) $where[] = ['enable', '=', $param['enable']];
        
        if (isset($param['id'])) $where[] = ['id', '=', $param['id']];

        if (!isset($where)) exception();
        
        $res = AdminModel::adminInfo($where);
        
        return $res;
    }

    /**
     * 管理员删除
     */
    public function adminDelete($param = [])
    {
        
        if (isset($param['id']) && !empty($param['id'])) $where[] = ['id', '=', $param['id']];

        if (!isset($where)) exception();
        
        return AdminModel::deleteData($where);
    }

    /**
     * 管理员批量删除
     */
    public function adminDeletes($param = [])
    {
        
        if (isset($param['idstr']) && !empty($param['idstr'])) $where[] = ['id', 'in', $param['idstr']];

        if (!isset($where)) exception();
        
        return AdminModel::deleteData($where);
    }

    /**
     * 角色详情
     */
    public function roleInfo($param = [])
    {

        if (isset($param['roleId'])) $where[] = ['id', '=', $param['roleId']];

        if (!isset($where)) exception();

        $info = AdminRoleModel::info($where);

        if (isset($info['ruleId']) && !empty($info['ruleId'])) $info['ruleId'] = explode(',', $info['ruleId']);

        return $info;
    }

    /**
     * 权限详情
     */
    public function ruleInfo($param = [])
    {

        if (isset($param['ruleId'])) $where[] = ['id', 'in', $param['ruleId']];

        if (isset($param['path_url'])) $where[] = ['path_url', '=', $param['path_url']];

        if (!isset($where)) exception();

        return AdminRuleModel::info($where);
    }

    /**
     * 权限【管理员、所有】
     */
    public function ruleAdminAll()
    {

        $adminLoginInfo = $this->adminLoginInfo();

        if ($adminLoginInfo['roleId'] != 0):

            $whereRole = [
                ['id', '=', $adminLoginInfo['roleId']],
                ['enable', '=', 2]                
            ];
            
            $infoRole = AdminRoleModel::info($whereRole);
            
            if (empty($infoRole)) exception('没有权限访问!');

            $ruleId = explode(',', $infoRole['ruleId']);

            $where[] = ['id', 'in', $ruleId];
            $child_where[] = ['id', 'in', $ruleId];
        endif;

        // $where[] = ['menu', '=', 2];
        $where[] = ['level', 'in', [0, 1]];
        // $where[] = ['pid', '=', 0];

        $parent_listsRule = AdminRuleModel::listsAll($where, '', 'order DESC');
        if(empty($parent_listsRule)) exception('没有可访问的权限');

        $child_where[] = ['level', 'in', [2]];
        $child_where[] = ['pid', '<>', 0];
        
        $child_listsRule = AdminRuleModel::listsAll($child_where);

        $return_data = self::mergeRuleData($parent_listsRule,$child_listsRule);

        return ['rules' => $return_data];
    }

    /**
     * 获取所有权限列表
     */

    public function rulesAlllist()
    {
        $where[] = ['enable', '=', 2];
        $field   = ['id, pid, path, path_url, level, auth_name, enable'];
        $listsRule = AdminRuleModel::listsAll($where, $field, 'order Desc')->toArray();
        if(empty($listsRule)) exception('权限列表获取失败');        
        $data     = AdminRoleModel::treeRuleList($listsRule);
        return $data;
    }

    // 父子权限组归纳合并
    protected function mergeRuleData($par_rulelist, $child_rulelist)
    {
        $return_data = $par_rulelist->toArray();
        $child_data  = $child_rulelist->toArray();
        // var_dump($child_data);
        foreach($return_data as &$v){
            foreach($child_data as &$c){
                if($c['pid'] === $v['id']){                    
                    $v['children'][] = $c;
                }
            }
        }
        return $return_data;
    }

    /**
     * 管理员添加编辑保存
     */
    public function adminAddEditSave($param = [])
    {
        $where = [];
        if (isset($param['password'])):
            if (empty($param['password'])):
                unset($param['password']);
            else:
                $param['truepass'] = $param['password'];
                $param['password'] = password_hash($param['password'], PASSWORD_DEFAULT);             
            endif;

            unset($param['password2']);
        endif;

        if(isset($param['id'])):
            $where[] = ['id', '=', $param['id']];
            unset($param['id']);
        endif;
        // 所属频道
        if(isset($param['channel']) && !empty($param['channel'])):
            $param['channel'] = implode(',', $param['channel']);
        endif;

        // 所属部门
        if(isset($param['depart']) && !empty($param['depart'])):
            $param['depart'] = implode(',', $param['depart']);
        endif;

        AdminModel::addEditSave($param, $where);
        return true;
    }

    public function updateEnable($userid, $param)
    {
        $res = AdminModel::addEditSave($param, [['id', '=', $userid]]);
        return $res;
    }

    /**
     * 获取权限列表
     */
    public function rullAdminList()
    {
        $list = AdminRuleModel::listsAll();
        return $list;
    }
    
    /**
     * 获取角色列表
     */
    public function rolesList()
    {        
        $list = AdminRoleModel::roleAdminList();
        return $list;
    }

    /**
     * 密码修改保存
     */
    public function useruppass($param) {
        if (empty($param['id']) || empty($param['newpass'])) exception('用户id，参数错误');
        $admininfo = AdminModel::info([['id', '=', $param['id']]]);

        if(!empty($admininfo['password']) && !password_verify($param['oldpass'], $admininfo['password'])) {
            exception('原始密码不正确，请重新输入');
        }
        
        return self::adminAddEditSave([
            'id' => $param['id'],
            'password' => $param['newpass']
        ]);
    }
    
}


?>